<template>
  <div id="app">
    <h1>{{ msg }}</h1>

    <h3>通过对象生成签名</h3>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="桶名">
        <el-input v-model="bucketName" placeholder="桶名"></el-input>
      </el-form-item>
      <el-form-item label="对象名称">
        <el-input v-model="objectName" placeholder="对象名称"></el-input>
      </el-form-item>
    </el-form>

    <H4>URL签名</H4>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="签名HTTP method">
        <el-input v-model="HTTPMethod" placeholder="PUT POST GET DELETE"></el-input>
      </el-form-item>
      <el-form-item label="签名过期时间 秒">
        <el-input v-model="expireDate" placeholder="expireDate"></el-input>
      </el-form-item>
      <el-form-item label="签名URL">
        <el-input v-model="presignedUrl" placeholder="URL"></el-input>
      </el-form-item>
      <el-form-item label="支持 GET PUT DELETE 操作对象">
      </el-form-item>
    </el-form>
    <p></p>

    <el-button type="primary" @click="submit1()">生成get签名URL(仅预览和下载使用)</el-button>
    <p></p>
    <el-button type="primary" @click="submit2()">生成put签名URL(仅上传和更新使用)</el-button>
    <p></p>
    <el-button type="primary" @click="submit3()">生成签名URL(自定义 HTTP method)</el-button>
    <p></p>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="上传字符串">
        <el-input v-model="objectContent" placeholder="objectContent"></el-input>
      </el-form-item>
      <el-form-item label="PUT 签名URL">
        <el-input v-model="presignedUrl" placeholder="URL"></el-input>
      </el-form-item>
      <el-button type="primary" @click="submit4()">上传字符串类型对象</el-button>
    </el-form>
    <p></p>

    <P>{{data}}</P>
  </div>
</template>

<script>

  var OSS = require("oss-js-client");

  var ossClient = new OSS.Client({
    // endPoint: "192.168.1.40",
    endPoint: "127.0.0.1",
    port: 9000,
    useSSL: false,
    accessKey: "username",
    secretKey: "password",
  });

  //base64转bolb
  function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(',');
    //注意base64的最后面中括号和引号是不转译的
    var _arr = arr[1].substring(0, arr[1].length - 2);
    var mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(_arr),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
      type: mime
    });
  };

  //将字符串转化为二进制的数据
  function strToBinary(str) {
    var result = [];
    var list = str.split("");
    for (var i = 0; i < list.length; i++) {
      if (i != 0) {
        //加空格，分割二进制
        result.push(" ");
      }
      var item = list[i];
      //将字符串转化为二进制数据
      var binaryStr = item.charCodeAt().toString(2);
      result.push(binaryStr);
    }
    return result.join("");
  }

  export default {
    name: "VueOSSObject",
    data() {
      return {
        bucketName: "mybucket2",
        objectName: "a.txt",
        objectContent: "a-Content",
        HTTPMethod: "GET",  //GET PUT POST
        presignedUrl: "",
        expireDate: 24 * 60 * 60,
        file: {},
        fileFormData: null,
        formInline: {},
        data: '',
        msg: "演示OSSClient-Object URL操作",
      };
    },
    methods: {
      onChange: function (event) {
        this.file = event.target.files[0]; // get input file object
        console.log(this.file);
      },

      //PUT URL签名 用于生成预览或下载对象 即使存储桶是私有的
      submit1: function () {
        //浏览器/移动客户端可能会指向此URL，以将对象直接预览或下载（即使它是私有的）
        //expires in a day. 过期时间
        ossClient.presignedGetObject(this.bucketName, this.objectName, this.expireDate, (err, presignedUrl) => {
          if (err) return console.log(err);

          console.log(presignedUrl);
          this.HTTPMethod = 'GET';
          this.presignedUrl = presignedUrl;
        });
      },

      //PUT URL签名 用于上传和更新对象 即使存储桶是私有的
      submit2: function () {
        //expires in a day.
        ossClient.presignedPutObject(this.bucketName, this.objectName, this.expireDate, (err, presignedUrl) => {
          if (err) return console.log(err);

          console.log(presignedUrl);
          this.HTTPMethod = "PUT";
          this.presignedUrl = presignedUrl;
        });
      },

      //自定义签名 URL签名 用于上传/更新/预览/下载/删除对象 即使存储桶是私有的
      submit3: function () {
        ossClient.presignedUrl(this.HTTPMethod, this.bucketName, this.objectName, this.expireDate, (err, presignedUrl) => {
          if (err) return console.log(err);

          console.log(presignedUrl);
          this.presignedUrl = presignedUrl;
        });
      },

      //使用URL签名 PUT请求  上传string对象
      //PUT URL签名 用于上传和更新对象 即使存储桶是私有的
      submit4: function () {

        //获取对象签名URL , 用于PUT请求上传对象
        ossClient.presignedPutObject(this.bucketName, this.objectName, this.expireDate, (err, presignedUrl) => {
          if (err) return console.log(err);

          console.log(presignedUrl);
          this.HTTPMethod = "PUT";
          this.presignedUrl = presignedUrl;
          this.uploadTxtByString(presignedUrl, this.objectContent)
        });
      },

      //上传string 字符串对象
      uploadTxtByString: function (presignedUrl, str) {

        let metaData = {
          'Content-Type': "text/plain",
        };

        //推荐 使用fetch发送请求
        //根据签名URL 上传对象(binary对象类型)
        fetch(presignedUrl, {
          method: 'PUT',
          body: str,
          headers: metaData
        })
          .then(response => response)
          .catch(error => console.error('Error:', error))
          .then(response => console.log('Success:', response));
      }

    }
  };
</script>

<style scope>
</style>
